var data_arr;
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            Table.api.init({
                extend: {
                    index_url: 'task/job/index' + (task_id ? '/ids/' + task_id : ''),
                    add_url: 'task/job/add' + (task_id ? '/tid/' + task_id : ''),
                    // edit_url: 'task/job/edit',
                    // del_url: 'task/job/del',
                    // multi_url: 'task/job/multi',
                    import_url: 'task/job/import' + (task_id ? '/tid/' + task_id : ''),
                    table: 'task_job',
                }
            });

            var table = $("#table");
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                showExport: true,
                // exportTypes: ['excel'],
                // showColumns: false,
                // showToggle: false，
                pageSize: 20,
                pageList: [20, 50],
                columns: [
                    [
                        /*{checkbox: true},*/
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'admin.nickname',
                            title: __('所属用户'),
                            // formatter: Table.api.formatter.label,
                            visible: requirejs.s.contexts._.config.config.admined
                        },
                        {
                            field: 'task.name',
                            title: __('所属任务')
                        },
                        /*{field: 'tid', title: __('Tid')},*/
                        {
                            field: 'number',
                            title: __('Number')
                        },
                        {
                            field: 'name',
                            title: __('Name')
                        },
                        {
                            field: 'company',
                            title: __('Company')
                        },
                        // {
                        //     field: 'called',
                        //     title: __('Called'),
                        //     visible: false,
                        //     searchList: {
                        //         "1": __('√')
                        //     }
                        // },
                        // {
                        //     field: 'called_text',
                        //     title: __('Called'),
                        //     operate: false
                        // },
                        {
                            field: 'calltime',
                            title: __('Calltime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'callgateway',
                            // visible: false,
                            title: __('Callgateway')
                        },
                        {
                            field: 'callstate',
                            title: __('Callstate'),
                            visible: false,
                            searchList: {
                                "success": __('callstate success'),
                                "fail": __('callstate fail')
                                // ,
                                // "none": __('callstate none')
                            }
                        },
                        {
                            field: 'callstate_text',
                            title: __('Callstate'),
                            operate: false
                        },
                        {
                            field: 'failreason',
                            title: __('Failreason'),
                            visible: false,
                            formatter: function (value, row, index, field) {
                                return __(value);
                            }
                        },
                        {
                            field: 'routernum',
                            title: __('话术轮数')
                        },
                        {
                            field: 'faqnum',
                            title: __('关键词')
                        },
                        {
                            field: 'taskcalltime',
                            title: __('通话时长')
                        },
                        {
                            field: 'grade',
                            title: __('通话评级')
                        },
                        {
                            field: 'read_status',
                            title: __('是否查看'),
                            table: table,
                            searchList: {
                                "0": __('未查看'),
                                "1": __('已查看')
                                // ,
                                // "none": __('callstate none')
                            },
                            formatter: function (value, row, index) {
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                if (value == 0) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-circle-o',
                                        title: __('未查看'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-add-white'
                                    });
                                } else if (value == 1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-check-circle-o',
                                        title: __('已查看'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-add-white'
                                    });
                                }
                                return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                                return value;
                            }
                        },
                        {
                            field: '',
                            title: __('语音评价'),
                            operate: false,
                            formatter: function (value, row, index) {
                                if (row.content == null) {
                                    row.content = "";
                                }
                                return '<input type="text" class="form-control text-center text-weigh" data-id="' + row.id + '" value="' + row.content + '" style="cursor:pointer;width:100px;padding:0;height:24px;display: inline-block;" onKeyPress="if(window.event.keyCode==13) enterfn(this)"  onblur="upperCase()"  onfocus="setStyle()" placeholder="请输入评价" title=""/>';
                            }
                        },
                        {
                            field: '',
                            title: __('操作'),
                            table: table,
                            operate: false,
                            buttons: [{
                                name: 'detail',
                                title: __('详情'),
                                icon: 'fa fa-list',
                                classname: 'btn-td btn-dialog',
                                extend: 'data-toggle="tooltip"',
                                url: 'task/job/detail'
                            }],
                            formatter: Table.api.formatter.operate
                        },
                        //{field: 'ivrstate', title: __('Ivrstate'), visible:false, searchList: {"started":__('ivrstate started'),"finished":__('ivrstate finished'),"none":__('ivrstate none')}},
                        //{field: 'ivrstate_text', title: __('Ivrstate'), operate:false},
                        //{field: 'queuestate', title: __('Queuestate'), visible:false, searchList: {"queued":__('queuestate queued'),"recepted":__('queuestate recepted'),"none":__('queuestate none')}},
                        //{field: 'queuestate_text', title: __('Queuestate'), operate:false},
                        //{field: 'receptionextension', title: __('Receptionextension')},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime}//,
                        //{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            $('.btn-singlesearchall').on('click', function () {
                // $('.form-control[name="grade"]').val("")
                $('.form-control[name="grade"]').val("");
                $('.form-control[name="callstate"]').val("");
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("全部客户搜索成功");
            });
            $('.btn-singlesearch').on('click', function () {
                // $('.form-control[name="grade"]').val("")
                $('.form-control[name="grade"]').val("");
                $('.form-control[name="callstate"]').val("success");
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("接通客户搜索成功");
            });
            $('.btn-singlesearcha').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="grade"]').val("a")
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("A类客户搜索成功");
            });
            $('.btn-singlesearchb').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="grade"]').val("b")
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("B类客户搜索成功");
            });
            $('.btn-singlesearchc').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="grade"]').val("c")
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("C类客户搜索成功");
            });
            $('.btn-singlesearchd').on('click', function () {
                $('.form-control[name="callstate"]').val("success");
                $('.form-control[name="grade"]').val("d")
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("D类客户搜索成功");
            });
            $('.btn-singlesearchfail').on('click', function () {
                $('.form-control[name="grade"]').val("");
                $('.form-control[name="callstate"]').val("fail");
                $('.btn-info[type="submit"]').trigger('click');
                Toastr.success("未接通客户搜索成功");
            });
            $(document).on("change", ".text-weigh", function () {
                $.post("/admin/task/job/line_edit?id=" + $(this).data('id') + "&content=" + $(this).val() + "", function (data) {
                    if (data.code == "200") {
                        // Toastr.success(data.msg);
                    } else {
                        Toastr.error(data.msg);
                    }
                });
            });
            $(document).on("mousemove", ".text-weigh", function () {
                $(this).attr('title', $(this).val());
            });
            $(document).on('click', '.btn-dialog', function (e) {
                $(this).find('i').css({'color':'#3c8dbc'});
                $(this).parent().parent().siblings().find('.btn-dialog').find('i').css({'color':'rgba(51,51,51,0.8)'});
                $.post("/admin/task/job/line_edit?id=" + $(this).attr('href').split("task/job/detail/ids/")[1] + "&action=1", function (data) {
                    if (data.code == "200") {
                        // Toastr.success(data.msg);
                        table.bootstrapTable('refresh');
                    }
                    // else {
                    //     Toastr.error(data.msg);
                    // }
                });
            });
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            // window.location.reload();
            $.get('/admin/task/job/getjson/ids/' + $('.job_id').text() + '', function (data) {
                    if (data === "error") {
                        $('.layui-layer-fast.layui-layer-iframe').hide()
                        Toastr.success('此明细暂无，敬请期待！')
                    } else {
                        data_arr = eval("(" + data + ")").flow_result
                        for (var i = 0; i < data_arr.length; i++) {
                            var date_value = timestampToTime(data_arr[i].voice.time);
                            if (data_arr[i].type == "robot") {
                                if (data_arr[i].voice.hint ==null) {
                                    data_arr[i].voice.hint="机器人合成语音";
                                }

                                if (data_arr[i].voice.path === undefined){
                                    $('.qa-text').append("<li class='human'><span>" + date_value + "</span><div><p><span>机器人合成语音：<i>" + data_arr[i].voice.hint + "</i></span></p></div><img src='/assets/img/jiqiren.png'/></li>");
                                }else{
                                    $('.qa-text').append("<li class='human'><span>" + date_value + "</span><div><audio src='" + data_arr[i].voice.path.split("public")[1]+ "' style='display: none;'></audio><img src='/assets/img/bofang.png' class='audios'/><p><span>话术名称：<i>" + data_arr[i].voice.hint + "</i><br></span></p></div><img src='/assets/img/jiqiren.png'/></li>");
                                }

                            } else if (data_arr[i].type == "human") {
                                $('.qa-text').append("<li class='robot'><img src='/assets/img/tx1.png'/><div><p><span>客户：<i>" + data_arr[i].voice.hint + "</i></span></i></p></div><span>" + date_value + "</span></li>");
                            }
                        }

                        $('.audio-detail').append('<a href=' + $('.file-ad').text().replace(' _', '%20_') + ' download=' + $('.file-ad').text().replace(' _', '%20_') + '>下载</a>');
                        var wxAudio = new Wxaudio({
                            ele: '.textaudio',
                            title: '通话详情',
                            disc: ' ',
                            src: $('.file-ad').text(),
                            width: ''
                        });
                        $('.wx-audio-state').on('click',function(){
                            $('.audios').attr('src', '/assets/img/bofang.png');
                        })
                        $('.audios').on('click', function () {
                            var pre = this.parentNode.getElementsByTagName('audio')[0];
                            pre.pause();
                            pre.currentTime = 0;
                            if ($(this).attr('src') == "/assets/img/bofang.png") {
                                pre.play();
                                $('.audios').attr('src', '/assets/img/bofang.png');
                                $(this).attr('src', '/assets/img/zanting.png');
                            } else {
                                pre.pause();
                                $(this).attr('src', '/assets/img/bofang.png');
                            }
                        })
                        $('audio').on('ended', function () {
                            $('.audios').attr('src', '/assets/img/bofang.png');
                        });
                        [].forEach.call(audios, function (i) {
                            i.addEventListener("play", pauseAll.bind(i));
                        })
                    }
                },
                'json');
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
var audios = document.getElementsByTagName("audio");

function pauseAll() {
    var self = this;
    [].forEach.call(audios, function (i) {
        i !== self && i.pause();
    })
}

function play() {
    wxAudio.audioPlay()
}

function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    if (date.getHours() < 10) {
        h = '0' + date.getHours() + ':';
    } else {
        h = date.getHours() + ':';
    }
    if (date.getMinutes() < 10) {
        m = '0' + date.getMinutes() + ':';
    } else {
        m = date.getMinutes() + ':';
    }
    if (date.getSeconds() < 10) {
        s = '0' + date.getSeconds();
    } else {
        s = date.getSeconds();
    }
    return Y + M + D + h + m + s;
}

function getCaption(obj) {
    var index = obj.lastIndexOf("public");
    obj = obj.substring(index + 6, obj.length);
    return obj;
}

function enterfn(thisinput) {
    $.post("/admin/task/job/line_edit?id=" + $(thisinput).data('id') + "&content=" + $(thisinput).val() + "", function (data) {
        if (data.code == "200") {
            // Toastr.success(data.msg);
            thisinput.blur();
        } else {
            Toastr.error(data.msg);
        }
    });
}

function setStyle() {
    $('.text-weigh').css({
        'cursor': 'default'
    });
}

function upperCase() {
    $('.text-weigh').css({
        'cursor': 'pointer'
    });
}